<?php
	
	/* Cette classe gère l'authentification des utilisateurs. Le login
	 * s'effectue en trois étapes : tentative de login en étudiant, si
	 * échec tentative de login en DDE, si échec tentative de login en
	 * admin.
	 */
	
	error_reporting(E_ALL);
	ini_set('display_errors', true);
	
	include_once "inc/defines.php";
	
	class Auth {
		
		public function __construct($login, $password) {
			$this->loggedIn = false;
			$db = new PDO(SERVER.":host=".HOST.";dbname=".BASE, USER, PASS);
			$sqlEtudiant = "SELECT login FROM ".ETUDIANT_TABLE." WHERE login = :login AND password = :password;";
			$sqlDDE = "SELECT login FROM ".DDE_TABLE." WHERE login = :login AND password = :password;";
			$sqlAdmin = "SELECT login FROM ".ADMIN_TABLE." WHERE login = :login AND password = :password;";
			
			//tentative de login en Etudiant (cas le plus courant)
			$this->login($db, $sqlEtudiant, $login, $password, ETUDIANT);
			
			//puis tentative de login en DDE sinon
			if(!$this->loggedIn)
				$this->login($db, $sqlDDE, $login, $password, DDE);
			
			//enfin tentative de login en Admin
			if(!$this->loggedIn)
				$this->login($db, $sqlAdmin, $login, $password, ADMIN);
		}
		
		public function login($db, $sql, $login, $password, $accountType) {
			$st = $db->prepare($sql);
			$st->bindValue(':login', $login, PDO::PARAM_STR);
			$st->bindValue(':password', $password, PDO::PARAM_STR);
			$st->execute();
			while($ligne = $st->fetch()) {
				if($login == $ligne[0]) {
					$this->accountType = $accountType;
					$this->loggedIn = true;
					$_SESSION["authLevel"] = $accountType;
					$_SESSION["login"] = $login;
					$db = null;
					break;
				}
			}
		}
		
		public static function secure($authLevel) {
			if(!isset($_SESSION["authLevel"]) || $_SESSION["authLevel"] != $authLevel) {
				$_SESSION["loginMessage"] = "Vous devez vous authentifier pour acc&eacute;der &agrave; cette page.";
				header("Location: ../../pages/login.php");
			}
		}
		
	}
	
?>
